"use client"

import { Button } from "@/components/ui/button"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"

interface EventLibrary {
  id: string
  name: string
  description: string | null
}

export default function GameSelectPage() {
  const router = useRouter()
  const [libraries, setLibraries] = useState<EventLibrary[]>([])
  const [selectedLibraries, setSelectedLibraries] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string>("")

  useEffect(() => {
    async function fetchLibraries() {
      try {
        const response = await fetch("/api/libraries")
        if (!response.ok) throw new Error("加载失败")
        const data = await response.json()
        setLibraries(data)
      } catch (err) {
        setError("无法加载事件库")
      } finally {
        setLoading(false)
      }
    }

    fetchLibraries()
  }, [])

  const toggleLibrary = (libraryId: string) => {
    setSelectedLibraries(prev =>
      prev.includes(libraryId)
        ? prev.filter(id => id !== libraryId)
        : [...prev, libraryId]
    )
  }

  const startGame = () => {
    if (selectedLibraries.length === 0) {
      setError("请至少选择一个事件库")
      return
    }
    router.push(`/game/play?libraries=${selectedLibraries.join(",")}`)
  }

  if (loading) return <div className="text-center p-8">加载中...</div>
  if (error) return <div className="text-center text-red-500 p-8">{error}</div>

  return (
    <div className="max-w-4xl mx-auto p-8">
      <h1 className="text-2xl font-bold mb-6">选择事件库</h1>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
        {libraries.map(library => (
          <div
            key={library.id}
            className={`p-4 border rounded-lg cursor-pointer transition-colors ${
              selectedLibraries.includes(library.id)
                ? "border-blue-500 bg-blue-50"
                : "border-gray-200 hover:border-blue-300"
            }`}
            onClick={() => toggleLibrary(library.id)}
          >
            <h3 className="font-semibold">{library.name}</h3>
            {library.description && (
              <p className="text-sm text-gray-600 mt-1">{library.description}</p>
            )}
          </div>
        ))}
      </div>

      {libraries.length === 0 && (
        <div className="text-center text-gray-500 p-8">
          暂无可用的事件库
        </div>
      )}

      <div className="flex justify-center">
        <Button
          onClick={startGame}
          disabled={selectedLibraries.length === 0}
          size="lg"
        >
          开始游戏
        </Button>
      </div>
    </div>
  )
} 